<script setup lang="ts">
import { defineProps, ref, onMounted, onUnmounted } from 'vue';
import { getFullUrl } from '#/utils/getImgUrl';

const props = defineProps({
  src: {
    type: String,
    required: true,
  },
});
const videoSrc = ref<string | null>(null);
const loading = ref(false);
const isComponentMounted = ref(true);

onMounted(() => {
  isComponentMounted.value = true;
  loadVideo(props.src);
});

onUnmounted(() => {
  isComponentMounted.value = false;
  // 清理 Blob URL 以避免内存泄漏
  if (videoSrc.value && videoSrc.value.startsWith('blob:')) {
    URL.revokeObjectURL(videoSrc.value);
  }
});

async function loadVideo(url: string) {
  try {
    if (!isComponentMounted.value) return;
    
    loading.value = true;
    const fileData = await getFullUrl(url);
    
    // 检查组件是否仍然挂载
    if (!isComponentMounted.value) return;
    
    console.log('fileData', fileData);
    
    // 如果返回的是 ArrayBuffer，转换为 Blob URL
    if (fileData instanceof ArrayBuffer) {
      const blob = new Blob([fileData], { type: 'video/mp4' });
      videoSrc.value = URL.createObjectURL(blob);
    } else if (typeof fileData === 'string') {
      // 如果返回的是 URL 字符串，直接使用
      videoSrc.value = fileData;
    } else {
      console.error('不支持的文件数据类型:', typeof fileData);
    }
    
    if (isComponentMounted.value) {
      loading.value = false;
    }
  } catch (error) {
    console.error('视频加载失败:', error);
    if (isComponentMounted.value) {
      loading.value = false;
    }
  }
}

const videoRef = ref<HTMLVideoElement | null>(null);

</script>

<template>
  <div class="video-container">
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">加载中...</div>
    </div>
    <video 
      ref="videoRef" 
      :src="videoSrc || undefined" 
      style="width: 100%; height: 100%;" 
      controls 
      preload="metadata"
      @loadstart="loading = true"
      @canplay="loading = false"
      @error="loading = false"
    />
  </div>
</template>

<style scoped>
.video-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  color: white;
  font-size: 14px;
}
</style>
